package org.ushio.nchu_22201406.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.ushio.common_module.entity.Bill;
import org.ushio.nchu_22201406.Feign.BillClient;
import org.ushio.nchu_22201406.service.balanceService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class balanceController {

    private final BillClient billClient;
    private final balanceService balanceService;

    @Autowired
    public balanceController(BillClient billClient, balanceService balanceService) {
        this.billClient = billClient;
        this.balanceService = balanceService;
    }
    @CrossOrigin(origins = "http://localhost:8080")
    @PutMapping("/balance")
    public ResponseEntity<?> updateBalance(@RequestBody Map<String, Object> payload) {
        String phoneNumber = (String) payload.get("phoneNumber");
        BigDecimal amount = new BigDecimal(payload.get("amount").toString());
        String paymentMethod = (String) payload.get("paymentMethod"); // 获取支付方式

        System.out.println("Received recharge request: phoneNumber=" + phoneNumber + ", amount=" + amount + ", paymentMethod=" + paymentMethod);
        balanceService.updateBalance(phoneNumber, amount);

        // 创建充值订单
        Bill bill = new Bill();
        String paymentReason="话费充值";
        bill.setPhoneNumber(phoneNumber);
        bill.setPaymentAmount(amount.doubleValue());
        bill.setPaymentMethod(paymentMethod);
        bill.setPaymentReason(paymentReason);
        bill.setPaymentDate(new java.sql.Date(System.currentTimeMillis())); // 当前日期
        ResponseEntity<Bill> response = billClient.createBill(bill);

        if (response.getStatusCode().is2xxSuccessful()) {
            return ResponseEntity.ok("Recharge successful");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Recharge failed");
        }
    }

}
